package com.kongchengji.spider.station.service;
import com.huaban.analysis.jieba.JiebaSegmenter;
import com.huaban.analysis.jieba.SegToken;
import com.kongchengji.spider.station.dao.PictureDao;
import com.kongchengji.spider.station.dao.PictureSetDao;
import com.kongchengji.spider.station.dao.SourceStationDao;
import com.kongchengji.spider.station.domain.PictureDO;
import com.kongchengji.spider.station.domain.PictureModelDO;
import com.kongchengji.spider.station.domain.PictureSetDO;
import com.kongchengji.spider.station.domain.SourceStationDO;
import com.kongchengji.spider.util.R;
import org.apache.catalina.util.URLEncoder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;


@Service
public class PictureModelService {
    @Autowired
    private PictureSetDao pictureSetDao;
    @Autowired
    private PictureDao pictureDao;
    @Autowired
    private SourceStationDao sourceStationDao;
    static ReentrantLock lock = new ReentrantLock();

    /**
     * 添加到数据库
     *
     * @param pictureModelDO 入库的数据
     * @return 返回入库成功标识
     * @throws Exception 入库失败抛出异常
     */
    @Transactional(rollbackFor = Exception.class)
    public R add(PictureModelDO pictureModelDO, int stationId) {

        PictureSetDO pictureSetDO = new PictureSetDO();
        //设置采集源网站id和套图品质
        pictureSetDO.setSourceStationId(pictureModelDO.getStationId());
        pictureSetDO.setQuality(pictureModelDO.getQuality());
        if (StringUtils.isNotBlank(pictureModelDO.getThumbnailUrl())) {
            pictureSetDO.setThumbnailUrl(pictureModelDO.getThumbnailUrl());
        }
        //添加栏目
        int lastIndex = addCategory(pictureModelDO.getSourceStationDOS(), stationId);
        pictureSetDO.setProgramName(pictureModelDO.getSourceStationDOS().get(lastIndex).getName());
        pictureSetDO.setTitle(StringUtils.trim(pictureModelDO.getTitle()));

        //判断看有没有同名标题的图集，不存在则添加，存在则返回图集主键
        //将标题分词后存储进对象
        titleParticiple(pictureSetDO);
        //判断有没有同名标题

        //图集入库
        pictureSetDao.add(pictureSetDO);

        int pictureSetId = pictureSetDO.getPictureSetId();
        for (String urlContent : pictureModelDO.getUrlContentList()) {
            PictureDO pictureDO = new PictureDO();
            pictureDO.setPictureSetId(pictureSetId);
            pictureDO.setPictureUrl(urlContent);
            pictureDao.add(pictureDO);
        }
        return R.ok();
    }

    /**
     *添加栏目
     * @param sourceStationDOS
     * @param stationId
     * @return 返回的栏目集合的最后角标
     */
    public int addCategory(List<SourceStationDO> sourceStationDOS, int stationId) {
        //层级关系
        StringBuilder stringBuilder = new StringBuilder();
        //添加站点
        stringBuilder.append(stationId);
        //栏目父级id
        int parentId = stationId;
        //1.先把栏目层级在数据库里in查询出对应的所有id
        List<String> programNames = new ArrayList<>();
        for (SourceStationDO sourceStationDO : sourceStationDOS) {
            programNames.add(sourceStationDO.getName());
        }
        //2.定义一个游标，先遍历ids数组，组装栏目层级关系
        List<Integer> ids = sourceStationDao.selectIdsByNames(programNames,stationId);
        int count = 0;
        for (; count < ids.size(); count++) {
            //排除站点
            if(stationId != ids.get(count)){
                stringBuilder.append(","+ids.get(count));
                parentId = ids.get(count);
            }
        }
        //3.如果遍历完ids数组游标的位置没有在集合sourceStationDOS的最后位置,则说明后面有未添加的栏目，在游标的后一位
        for (;count < sourceStationDOS.size(); count++) {
            SourceStationDO sourceStationDO = sourceStationDOS.get(count);
            sourceStationDO.setStationId(stationId);
            sourceStationDO.setParentId(parentId);
            //4.将此栏目添加数据库。
            sourceStationDao.add(sourceStationDO);
            parentId = sourceStationDO.getId();
            stringBuilder.append("," + sourceStationDO.getId());
            sourceStationDO.setRelation(stringBuilder.toString());
            sourceStationDao.updateRelation(sourceStationDO);
        }

        return sourceStationDOS.size() - 1;

    }

    /**
     * 将图集分词后设置进pictureSetDO对象
     *
     * @param pictureSetDO
     */
    private void titleParticiple(PictureSetDO pictureSetDO) {
        String title = pictureSetDO.getTitle();
        JiebaSegmenter segmenter = new JiebaSegmenter();
        List<SegToken> list = segmenter.process(title, JiebaSegmenter.SegMode.INDEX);
        StringBuilder stringBuilder = new StringBuilder();
        for (SegToken segToken : list) {
            if(segToken.word.trim().length() == 0){
                continue;
            }
            String wordUrlEncode = URLEncoder.DEFAULT.encode(segToken.word, Charset.defaultCharset());
            wordUrlEncode = StringUtils.replaceAll(wordUrlEncode, "%", "");
            stringBuilder.append("+" + wordUrlEncode);
        }
        stringBuilder.deleteCharAt(0);
        pictureSetDO.setTitleParticiple(stringBuilder.toString());

    }


}
